package com.jhws.business.comm.controller;

import java.io.IOException;
import java.math.BigInteger;
import java.util.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jhws.common.base.bo.JsonRespData;
import com.jhws.business.comm.service.RoomService;
import com.jhws.util.AccountsUtils;
import com.jhws.util.ObjectUtils;
import net.sf.json.JSONArray;

import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.jhws.business.comm.bo.TblBuildingDimBo;
import com.jhws.business.comm.bo.TblCommDimBo;
import com.jhws.common.base.bo.Global;
import com.jhws.common.MyRequest;
import com.jhws.business.comm.service.ITblAreaDimService;
import com.jhws.business.comm.service.ITblBuildingDimService;
import com.jhws.business.comm.service.ITblCommDimService;
import com.jhws.sys.menu.service.ITblMenuDimService;
import com.jhws.sys.appUser.service.ITblSipAcountDimService;
import com.jhws.sys.user.service.ITblUserDimService;
import com.jhws.util.commUtil;

/**
 * @author : Alex Tan
 * @Create : 2016-10-25 下午2:37:28
 * @Comment : 单元相关控制器
 */
@Controller
@RequestMapping({"/BuildingCtrl", "/BuildingsCtrl", "/building"})
public class BuildingCtrl {
    @Resource
    protected ITblSipAcountDimService ITblSipAcountDimService;
    @Resource
    protected ITblBuildingDimService ITblBuildingDimService;
    @Resource
    protected ITblAreaDimService ITblAreaDimService;
    @Resource
    protected ITblCommDimService ITblCommDimService;
    @Resource
    protected ITblMenuDimService ITblMenuDimService;
    @Resource
    protected ITblUserDimService ITblUserDimService;
    @Resource
    protected RoomService roomService;

    @RequestMapping("query.x")
    @ResponseBody
    public JsonRespData query(@RequestParam Map param)
            throws java.lang.Exception {
        return new JsonRespData("", 1, ITblBuildingDimService.findBuildingListPage(param));
    }


    @RequestMapping("modify.x")
    @ResponseBody
    public JsonRespData modify(TblBuildingDimBo building) throws Exception {
        if (building != null && !building.getBuildingCode().isEmpty()) {
            TblBuildingDimBo bo = ITblBuildingDimService.findTblBuildingDimById(building.getBuildingCode());
            ObjectUtils.copyPropertiesIgnoreNull(building, bo);
            ITblBuildingDimService.save(bo);
            roomService.saveRoomsByBuilding(bo);
            return new JsonRespData("", 1, "");
        }

        return new JsonRespData("", -1, "参数错误");

    }

    /**
     * 批量修改整个小区的楼层和房间数目
     *
     * @param commCode
     * @param floors
     * @param rooms
     * @return
     * @throws Exception
     */
    @RequestMapping("modifyCommFloorAndRoom.x")
    @ResponseBody
    public JsonRespData modifyCommFloorAndRoom(String commCode, String floors, String rooms) throws Exception {
        List<TblBuildingDimBo> list = ITblBuildingDimService.findTblBuildingDimByWhere("where 1=1 and comm_code = '" + commCode + "'");
        for (TblBuildingDimBo b : list) {
            if (StringUtils.isNotEmpty(floors))
                b.setUnitNumber(Integer.valueOf(floors));
            if (StringUtils.isNotEmpty(rooms))
                b.setRoomNumber(Integer.valueOf(rooms));
            ITblBuildingDimService.save(b);
            roomService.saveRoomsByBuilding(b);
        }
        return new JsonRespData("", 1, "");
    }

    /**
     * 批量修改所选的多条楼栋信息
     *
     * @param buildings
     * @return
     * @throws Exception
     */
    @RequestMapping("modifyBatchs.x")
    @ResponseBody
    public JsonRespData modifyBatchs(@RequestBody TblBuildingDimBo[] buildings) throws Exception {

        for (TblBuildingDimBo building : buildings) {
            TblBuildingDimBo b = ITblBuildingDimService.findTblBuildingDimById(building.getBuildingCode());
            ObjectUtils.copyPropertiesIgnoreNull(building, b);
            ITblBuildingDimService.save(b);
            roomService.saveRoomsByBuilding(b);
        }
        return new JsonRespData("", 1, "");
    }

    @RequestMapping("remove.x")
    @ResponseBody
    public JsonRespData remove(@RequestBody TblBuildingDimBo[] buildings)
            throws Exception {
        if (buildings.length > 0) {
            for (TblBuildingDimBo building : buildings)
                ITblBuildingDimService.removeDim(building.getBuildingCode());
        } else {
            return new JsonRespData("", -1, "参数不正确");
        }
        return new JsonRespData("", 1, "");

    }

    @RequestMapping("removeByComm.x")
    @ResponseBody
    public JsonRespData remove(String commCode) throws Exception {
        if (StringUtils.isNotEmpty(commCode)) {
            ITblBuildingDimService.removeBuildingByComm(commCode);
        } else {
            return new JsonRespData("", -1, "参数不正确");
        }
        return new JsonRespData("", 1, "");

    }

    @RequestMapping("findBuilding.x")
    public String findBuildingDimList(HttpServletRequest request, HttpServletResponse response)
            throws java.lang.Exception {
        String commCode = MyRequest.GetString(request, "commCode");
        commCode = commUtil.appendZero(commCode);

        if (StringUtils.isEmpty(commCode)) {
            return "null";
        }
        String whereStr = "where comm_code = '" + commCode + "'";
        whereStr += " order by CAST(building_name AS DECIMAL)  ";
        List<TblBuildingDimBo> boList = ITblBuildingDimService.findTblBuildingDimByWhere(whereStr);
        request.setAttribute("boList", boList);

        try {
            JSONArray array = JSONArray.fromObject(boList);
            JSONArray ja = JSONArray.fromObject(array);
            request.setAttribute("ja", ja);
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(ja.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "null";
    }

    /**
     * @Comment: 当新建小区数据后，需要再度新增楼栋单元时，调用
     * @Param:
     */
    @RequestMapping("insertBuildingsSave.x")
    @ResponseBody
    public JsonRespData insertBuildingsSave(String commCode, String commName, @RequestParam String[] buildingData) throws Exception {

        Map<String, String> map = new HashMap<>();
        for (String line : buildingData) {
            String[] params = line.split("-");
            if (params.length < 5)
                continue;

            String where = "where 1=1 and comm_code = '" + commCode + "' and section_name = '" + params[0] + "' and areas_in_section = '" + params[1] + "' and building_name = '" + params[3] + "'";
            List<TblBuildingDimBo> list = ITblBuildingDimService.findTblBuildingDimByWhere(where);
            if (list != null && list.size() != 0)
                return new JsonRespData("", -1, "该数据已存在:" + params[0] + "区" + params[1] + "栋" + params[3] + "单元");

            TblBuildingDimBo buildingDimBo = new TblBuildingDimBo();
            buildingDimBo.setSectionName(params[0]);                     //区域
            buildingDimBo.setAreasInSection(params[1]);                     //区域内楼栋编号
            buildingDimBo.setAreaAliasName(params[2]);                   //楼栋别名
            buildingDimBo.setBuildingName(Integer.valueOf(params[3]) + "");                    //单元号
            buildingDimBo.setUnitNumber(Integer.valueOf(params[4]));     //单元楼层数
            buildingDimBo.setRoomNumber(Integer.valueOf(params[5]));     //每层房间数
            buildingDimBo.setDevNumber(Integer.valueOf(params[6]));     //每单元设备数

            buildingDimBo.setCommCode(commCode);
            buildingDimBo.setCommName(commName);

            if (!"none".equals(params[7]))
                map.put(params[0] + "-" + params[1], params[7]);

            if (Integer.valueOf(params[8]) == Global.BUILDING_NORMAL) {
                buildingDimBo.setBuildingAliasName(AccountsUtils.appendZeroBuilding(buildingDimBo.getBuildingName()) + "单元");
                buildingDimBo.setBuildingType(Global.BUILDING_NORMAL);
            } else if (Integer.valueOf(params[8]) == Global.BUILDING_VILLA) {
                buildingDimBo.setBuildingAliasName(AccountsUtils.appendZeroBuilding(buildingDimBo.getBuildingName()) + "号别墅");
                buildingDimBo.setBuildingType(Global.BUILDING_VILLA);
            }

            String areaName = map.get(params[0] + "-" + params[1]);

            if (areaName == null) {
                BigInteger maxArea = ITblBuildingDimService.getMaxBuildingNum(commCode);
                if (maxArea != null)
                    areaName = maxArea.longValue() + 1 + "";
            }
            areaName = areaName == null ? "1" : areaName;
            buildingDimBo.setAreaName(Integer.valueOf(areaName) + "");
            ITblBuildingDimService.save(buildingDimBo);
            map.put(params[0] + "-" + params[1], areaName);
        }
        return new JsonRespData("", 1, "新增楼栋成功!");
    }

    @RequestMapping("insertBuildings.x")
    public ModelAndView insertBuildings(String commCode, String commName) {
        ModelAndView mv = new ModelAndView();
        mv.addObject("commCode", commCode);
        mv.addObject("commName", commName);
        mv.setViewName("business/buildingDim/insertBuildings");
        return mv;
    }

    @RequestMapping("selectBuildings.x")
    ModelAndView selectBuildings(String Owner) throws Exception {

        ModelAndView mv = new ModelAndView();

        List<TblCommDimBo> commList = ITblUserDimService.getUserComms(ITblUserDimService.currentUser());
        if (commList.size() != 0) {
            if (!SecurityUtils.getSubject().hasRole(Global.ROLE_PROPERTY_ADMIN))
                mv.addObject("commDimList", commList);
            else
                mv.addObject("commDimBo", commList.get(0));

        }

        if (Owner != null)
            mv.addObject("owner", "true");

        mv.setViewName("business/buildingDim/selectBuilding");
        return mv;
    }

    @RequestMapping("getUnitsInfo.x")
    @ResponseBody
    public String getBuidingsInfo(javax.servlet.http.HttpServletRequest request,
                                  javax.servlet.http.HttpServletResponse response, String commCode) {

        try {
            List<TblBuildingDimBo> list = ITblBuildingDimService.findTblBuildingDimByWhere("where 1=1 and comm_code = '" + commCode + "'");
            //request.setAttribute("boList", list);
            JSONArray array = JSONArray.fromObject(list);
            JSONArray ja = JSONArray.fromObject(array);
            request.setAttribute("ja", ja);
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(ja.toString());

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return null;
    }

    /**
     * excel导出需要的楼栋信息表，校验需要的数据
     *
     * @param commCode
     * @return
     */
    @RequestMapping("getUnitsInfoForExport.x")
    @ResponseBody
    public JsonRespData getUnitsInfoForExport(String commCode) {
        if (StringUtils.isEmpty(commCode))
            return new JsonRespData("", -1, "小区不能为空!");

        return new JsonRespData("", 1, ITblBuildingDimService.getUnitsInfoForExport(commCode));
    }

    /**
     * 用于小区信息选择
     *
     * @param commCode     小区编号
     * @param buildingCode 楼栋编号
     * @param unitCode     单元编号
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    @RequestMapping("getBuidingsInfoProcessed.x")
    @ResponseBody
    public JsonRespData getBuidingsInfoProcessed(String commCode, String buildingCode, String unitCode) throws Exception {
        HashedMap map = new HashedMap();
        if (!com.jhws.util.StringUtils.isEmpty(commCode) && com.jhws.util.StringUtils.isEmpty(buildingCode) && com.jhws.util.StringUtils.isEmpty(unitCode)) {

            //如果是超级管理员将别墅楼栋也返回，便于查找问题
            String buildingType = " and building_type = '" + Global.BUILDING_NORMAL + "' ";
            if (SecurityUtils.getSubject().hasRole(Global.ROLE_SUPPER_ADMIN)) {
                buildingType = "";
            }

            List<TblBuildingDimBo> list = ITblBuildingDimService.findTblBuildingDimByWhere(
                    "where 1=1 and comm_code = '" + commCode + "'" + buildingType + " group by area_name order by cast(area_name as int) ASC");
            List<String> buildings = new ArrayList<>();
            List<String> buildingsAliasName = new ArrayList<>();
            for (TblBuildingDimBo tblBuildingDimBo : list) {
                buildingsAliasName.add(com.jhws.util.StringUtils.isNotEmpty(tblBuildingDimBo.getAreaAliasName()) ? tblBuildingDimBo.getAreaAliasName() : appendZero(tblBuildingDimBo.getAreaName()) + '栋');
                buildings.add(appendZero(tblBuildingDimBo.getAreaName()));
            }
            map.put("buildings", buildings);
            map.put("buildingsAliasName", buildingsAliasName);
        } else if (!com.jhws.util.StringUtils.isEmpty(commCode) && !com.jhws.util.StringUtils.isEmpty(buildingCode) && com.jhws.util.StringUtils.isEmpty(unitCode)) {
            List<TblBuildingDimBo> list = ITblBuildingDimService.findTblBuildingDimByWhere(
                    "where 1=1 and comm_code = '" + commCode + "'" + " and area_name = '" + Integer.valueOf(buildingCode) + "' order by cast(building_name as int) ASC");
            List<String> units = new ArrayList<>();
            List<String> unitAlias = new ArrayList<>();
            for (TblBuildingDimBo tblBuildingDimBo : list) {
                units.add(appendZero(tblBuildingDimBo.getBuildingName()));
                unitAlias.add(tblBuildingDimBo.getBuildingAliasName());
            }
            map.put("units", units);
            map.put("unitAlias", unitAlias);
        } else if (!com.jhws.util.StringUtils.isEmpty(commCode) && !com.jhws.util.StringUtils.isEmpty(buildingCode) && !com.jhws.util.StringUtils.isEmpty(unitCode)) {
            List<TblBuildingDimBo> list = ITblBuildingDimService.findTblBuildingDimByWhere(
                    "where 1=1 and comm_code = '" + commCode + "'" + " and area_name = '" + Integer.valueOf(buildingCode) + "' and building_name = '" + Integer.valueOf(unitCode) + "'");
            List<String> roomList;
            LinkedHashMap floors = new LinkedHashMap();
            for (TblBuildingDimBo tblBuildingDimBo : list) {
                //加入楼栋
                for (int i = 1; i <= tblBuildingDimBo.getUnitNumber(); i++) {
                    String floorCode = appendZero(String.valueOf(i));
                    roomList = new ArrayList<>();
                    //加入房间
                    for (int j = 1; j <= tblBuildingDimBo.getRoomNumber(); j++) {
                        roomList.add(appendZero(String.valueOf(j)));
                    }
                    floors.put(floorCode, roomList);
                }
            }
            map.put("floors", floors);
        }
        return new JsonRespData("", 1, map);
    }

    @RequestMapping("getManagerInfo.x")
    @ResponseBody
    public String getManagerInfo(javax.servlet.http.HttpServletRequest request,
                                 javax.servlet.http.HttpServletResponse response, String commCode) {
        try {
            List<TblCommDimBo> tList = ITblCommDimService
                    .findTblCommDimByWhere("where 1=1 and comm_code = '" + commCode + "'");
            JSONArray array = JSONArray.fromObject(tList);
            JSONArray ja = JSONArray.fromObject(array);
            request.setAttribute("ja", ja);
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(ja.toString());
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping("getUnitDevNum.x")
    @ResponseBody
    public JsonRespData getUnitDevNum(String commCode, String buildingCode, String unitCode) throws Exception {
        return new JsonRespData("", 1, ITblBuildingDimService.getUnitDevNumber(commCode + buildingCode + unitCode));
    }

    private String appendZero(String num) {
        if (num.length() == 1)
            return "0" + num;
        else
            return num;
    }

    @RequestMapping("debugForGenBuildingAliasName.x")
    @ResponseBody
    public JsonRespData debugForGenBuildingAliasName() throws Exception {
        int count = 0;
        List<TblBuildingDimBo> buildings = ITblBuildingDimService.findTblBuildingDimByWhere("where area_alias_name = ''");
        if (buildings != null && buildings.size() != 0) {
            for (TblBuildingDimBo building : buildings) {
                building.setAreaAliasName(AccountsUtils.appendZeroBuilding(building.getAreaName()) + "栋");
                ITblBuildingDimService.save(building);
                count++;
            }
        }
        return new JsonRespData("", 1, "成功修改" + count + "条数据");
    }

    @RequestMapping("debugForGenUnitAliasName.x")
    @ResponseBody
    public JsonRespData debugForGenUnitAliasName(String type) throws Exception {
        int count = 0;
        List<TblBuildingDimBo> buildings = ITblBuildingDimService.findTblBuildingDimByWhere("where 1=1");
        for (TblBuildingDimBo building : buildings) {
            if ("back".equals(type)) {
                building.setAreaName("" + Integer.valueOf(building.getAreaName()));
                building.setBuildingName("" + Integer.valueOf(building.getBuildingName()));
            } else {
                building.setAreaName(AccountsUtils.appendZeroBuilding(building.getAreaName()));
                building.setBuildingName(AccountsUtils.appendZeroBuilding(building.getBuildingName()));
                if (StringUtils.isEmpty(building.getBuildingAliasName())) {
                    if (building.getBuildingType() == Global.BUILDING_NORMAL) {
                        building.setBuildingAliasName(building.getBuildingName() + "单元");
                        building.setBuildingType(building.getBuildingType());
                    } else if (building.getBuildingType() == Global.BUILDING_VILLA) {
                        building.setBuildingAliasName(building.getBuildingName() + "号别墅");
                        building.setBuildingType(building.getBuildingType());
                    }
                }
            }
            ITblBuildingDimService.save(building);
            count++;
        }

        return new JsonRespData("", 1, "成功写入" + count + "条数据");
    }
}
